package com.mvc.annotation;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mvc.util.ActionFileFilter;
import com.mvc.util.FileUtil;

public class AnnotationHandler implements IActionAnnotation {

	public Map<String,String> getActionAnnotation(String actionPackages) {
		Map<String,String> hashMap = new HashMap<String,String>();
		try {
			if("default".equals(actionPackages)){
				List<String> classNameList = getClassNameList(actionPackages);
				for (String className : classNameList) {
					System.out.println("load actino controller: " + className);
					Class<?> cls = Class.forName(className);
					Method[] methods = cls.getDeclaredMethods();
					for(Method method : methods){
						if(method.isAnnotationPresent(ActionMapping.class)){
							ActionMapping actionMapping = method.getAnnotation(ActionMapping.class);
							System.out.println(actionMapping.value());
							hashMap.put(actionMapping.value(), className);
						}
					}
				}
			}else{
				String[] actionPackageArr = actionPackages.split(",");
				for(String actionPackage : actionPackageArr){
					System.out.println("load actino controller: " + actionPackage);
					Class<?> cls = Class.forName(actionPackage);
					Method[] methods = cls.getDeclaredMethods();
					for(Method method : methods){
						if(method.isAnnotationPresent(ActionMapping.class)){
							ActionMapping actionMapping = method.getAnnotation(ActionMapping.class);
							System.out.println(actionMapping.value());
							hashMap.put(actionMapping.value(), actionPackage);
						}
					}
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return hashMap;
	}

	public List<String> getClassNameList(String actionPackages) {
		List<String> fileNameList = new ArrayList<String>();
		String rootPath = this.getClass().getClassLoader().getResource("/").getPath();
		List<String> fileList = FileUtil.getAllActionFiles(rootPath, new ActionFileFilter());
		rootPath = rootPath.replace("/", ".").replace("\\", ".");
		if (rootPath.indexOf(".") == 0) {
			rootPath = rootPath.substring(1);
		}
		for (String fileName : fileList) {
			fileName = fileName.replace("/", ".").replace("\\", ".").replace(rootPath, "");
			fileName = fileName.substring(0, fileName.lastIndexOf(".class"));
			fileNameList.add(fileName);
		}
		return fileNameList;
	}

	public static void main(String[] args) {
		AnnotationHandler ah = new AnnotationHandler();
		ah.getActionAnnotation("");
	}
}
